<template>
	<view>
		<view style="width: 100%; float: left; height: 10vh;">
			<view class="list_canting" @click="dindan" >
				<image :src="list.img"
					style="width: 70rpx; height: 70rpx; margin-left: 10px; margin-top: 15rpx; float: left;"></image>
				<view style="float: left; line-height: 100rpx; margin-left: 10px;">{{list.name}}</view>
				<image src="/static/fh.png"
					style="width: 40rpx; height: 30rpx; float: right; margin-right: 20rpx; margin-top: 35rpx;"></image>
			</view>
		</view>
		<view style="width: 100%; float: left; height: 90vh; float: left;">
			<view class="menu-page">
			
				<!-- 左侧分类导航 -->
				<scroll-view scroll-y class="nav-left">
					<view v-for="(category, index) in categories" :key="category.id" class="nav-item"
						:class="{active: activeCategory == index}" @click="switchCategory(category.sub_list,index)">
						{{category.name}}
					</view>
				</scroll-view>
			
				<!-- 右侧商品列表 -->
				<scroll-view scroll-y class="food-right" @scroll="onScroll">
					<!-- <view v-for="(category, index) in categories" :key="category.id" class="food-group"
						:id="'group-' + index"> -->
						<view class="group-title">{{category.name}}</view>
						<view v-for="food in foods" :key="food.id" class="food-item">
							<image :src="food.pic" class="food-img" mode="aspectFill"></image>
							<view class="food-info">
								<text class="food-name">{{food.name}}</text>
								<text class="food-desc">{{food.description}}</text>
								<text class="food-price">¥{{food.price.toFixed(2)}}</text>
							</view>
							<view class="food-action">
								<button v-if="cart[food.id]" class="action-btn minus"
									@click="updateCart(food.id, -1)">-</button>
								<text v-if="cart[food.id]" class="action-count">{{cart[food.id]}}</text>
								<button class="action-btn plus" @click="updateCart(food.id, 1)">+</button>
							</view>
						</view>
					<!-- </view> -->
				</scroll-view>
			
				<!-- 购物车底部栏 -->
				<view class="cart-bar" v-if="totalCount > 0" @click="goToCart">
					<view class="cart-icon">
						<uni-icons type="cart" size="28" color="#fff"></uni-icons>
						<text class="cart-badge">{{totalCount}}</text>
					</view>
					<text class="cart-total">¥{{totalPrice.toFixed(2)}}</text>
					<text class="cart-btn">去结算</text>
				</view>
			</view>
		</view>

		
	</view>
</template>

<script>
	import {

		storeInfo,
		getMenus

	} from '@/request/home.js'
	export default {
		data() {
			return {
				activeCategory: 0,
				scrollTop: 0,
				categoryTops: [], // 存储每个分类的顶部位置
				categories: [],
				foods:[
					{id: 101, name: "招牌牛肉面", price: 28, description: "精选牛肉，慢火炖煮", image: "/static/foods/1.jpg", categoryId: 1},
					{id: 102, name: "香辣鸡腿堡", price: 18, description: "酥脆鸡腿，香辣可口", image: "/static/foods/2.jpg", categoryId: 1},
					{id: 201, name: "红烧牛肉面", price: 25, description: "精选牛肉，慢火炖煮", image: "/static/foods/3.jpg", categoryId: 2},
					{id: 202, name: "番茄鸡蛋面", price: 18, description: "酸甜可口", image: "/static/foods/4.jpg", categoryId: 2},
					{id: 301, name: "薯条", price: 10, description: "金黄酥脆", image: "/static/foods/5.jpg", categoryId: 3},
					{id: 401, name: "可乐", price: 8, description: "冰爽可口", image: "/static/foods/6.jpg", categoryId: 4}
				],
			
				cart: {}, // 购物车数据 {商品ID: 数量}
				list:"",
			}
		},
		computed: {
			// 购物车商品总数量
			totalCount() {
				return Object.values(this.cart).reduce((total, num) => total + num, 0)
			},
			// 购物车总金额
			totalPrice() {
				return Object.keys(this.cart).reduce((total, id) => {
					const food = this.foods.find(item => item.id == id)
					return total + (food ? food.price * this.cart[id] : 0)
				}, 0)
			}
		},
		onLoad() {
			this.listtab()
		
			this.loadCart()
			this.shiopng()
		},
		methods: {
			listtab() {
				
				var params = {
					alipay_user_id: "2088912672015825",
					enterprise_id: 9,
					store_id: "23",
					user_id: 44419
				}
				storeInfo(params).then((res) => {
					
					this.list = res.data
				}).catch((err) => {
					console.log('失败', err);
				});

			},
			shiopng(){
				
				var params = {
					alipay_user_id: "2088912672015825",
					enterprise_id: 9,
					store_id: 23,
					user_id: 44419,
				}
				getMenus(params).then((res) => {
					console.log('成功', res);
					this.foods = res.data[0].sub_list
					this.categories = res.data
					
				}).catch((err) => {
					console.log('失败', err);
				});
			},
			// 获取指定分类的商品
			getFoodsByCategory(categoryId) {
				return this.foods.filter(food => food.categoryId === categoryId)
			},

			// 切换分类
			switchCategory(item,index) {
				console.log(index)
				this.foods = item
				this.activeCategory = index
			},

			// 滚动事件处理
			onScroll(e) {
				const scrollTop = e.detail.scrollTop
				// 计算当前滚动位置对应的分类
				for (let i = 0; i < this.categoryTops.length; i++) {
					if (scrollTop >= this.categoryTops[i] && scrollTop < (this.categoryTops[i + 1] || Infinity)) {
						if (this.activeCategory !== i) {
							this.activeCategory = i
						}
						break
					}
				}
			},

			// 更新购物车
			updateCart(foodId, num) {
				// 使用Vue.set确保响应式
				if (!this.cart[foodId]) {
					this.$set(this.cart, foodId, 0)
				}

				const newNum = this.cart[foodId] + num
				if (newNum <= 0) {
					this.$delete(this.cart, foodId)
				} else {
					this.cart[foodId] = newNum
				}

				// 保存到本地存储
				this.saveCart()

				// 显示反馈
				if (num > 0) {
					uni.showToast({
						title: '已添加',
						icon: 'success',
						duration: 800
					})
				}
			},

			// 保存购物车数据
			saveCart() {
				try {
					uni.setStorageSync('cart', this.cart)
				} catch (e) {
					console.error('保存购物车失败:', e)
				}
			},

			// 加载购物车数据
			loadCart() {
				try {
					const cart = uni.getStorageSync('cart')
					if (cart) {
						this.cart = cart
					}
				} catch (e) {
					console.error('加载购物车失败:', e)
				}
			},

			// 跳转到购物车
			goToCart() {
				// 将购物车数据传递到下一页
				const cartData = Object.keys(this.cart).map(id => {
					const food = this.foods.find(item => item.id == id)
					return {
						id: food.id,
						name: food.name,
						price: food.price,
						image: food.pic,
						count: this.cart[id]
					}
				})
               console.log(cartData)
				uni.navigateTo({
					url: `/pages/index/confirm?data=${encodeURIComponent(JSON.stringify(cartData))}`,
					success: () => {
						// 清空当前购物车
						this.cart = {}
						this.saveCart()
					}
				})
			},

			// 计算每个分类的顶部位置
			calculateCategoryTops() {
				const query = uni.createSelectorQuery().in(this)
				this.categoryTops = []

				this.categories.forEach((_, index) => {
					query.select(`#group-${index}`).boundingClientRect(res => {
						if (res) {
							this.categoryTops.push(res.top)
						}
					}).exec()
				})
			}
		},
		
		onReady() {
			// 页面渲染完成后计算分类位置
			setTimeout(() => {
				this.calculateCategoryTops()
			}, 300)
		}
	}
</script>

<style scoped>
	.list_canting {
		width: 90%;
		height: 100rpx;
		float: left;
		margin-left: 5%;
		background: #fff;
		border-radius: 10px;
		margin-top: 10px;
	}

	.menu-page {
		display: flex;
		height: 80vh;
		background-color: #f5f5f5;
		padding-bottom: 50px;
		box-sizing: border-box;
		
	}

	/* 左侧分类导航 */
	.nav-left {
		width: 25%;
		height: 100%;
		background-color: #f8f8f8;
	}

	.nav-item {
		padding: 20px 10px;
		text-align: center;
		font-size: 14px;
		color: #666;
		border-left: 3px solid transparent;
	}

	.nav-item.active {
		color: #1296db;
		font-weight: bold;
		background-color: #fff;
		border-left: 3px solid #1296db;
	}

	/* 右侧商品列表 */
	.food-right {
		width: 75%;
		height: 100%;
		padding: 0 10px;
		box-sizing: border-box;
	}

	.food-group {
		margin-bottom: 15px;
	}

	.group-title {
		padding: 15px 0;
		font-size: 16px;
		font-weight: bold;
		color: #333;
		border-bottom: 1px solid #eee;
	}

	.food-item {
		display: flex;
		padding: 15px;
		margin: 10px 0;
		background-color: #fff;
		border-radius: 8px;
		position: relative;
	}

	.food-img {
		width: 80px;
		height: 80px;
		border-radius: 4px;
	}

	.food-info {
		flex: 1;
		padding-left: 15px;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.food-name {
		font-size: 16px;
		font-weight: bold;
		color: #333;
	}

	.food-desc {
		font-size: 12px;
		color: #999;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.food-price {
		font-size: 16px;
		color: #1296db;
		font-weight: bold;
	}

	.food-action {
		position: absolute;
		right: 15px;
		bottom: 15px;
		display: flex;
		align-items: center;
	}

	.action-btn {
		width: 25px;
		height: 25px;
		line-height: 25px;
		text-align: center;
		border-radius: 50%;
		font-size: 16px;
		padding: 0;
		margin: 0;
	}

	.action-btn.plus {
		background: #1296db;
		color: #fff;
	}

	.action-btn.minus {
		border: 1px solid #1296db;
		color: #1296db;
		background: #fff;
	}

	.action-count {
		margin: 0 8px;
		min-width: 20px;
		text-align: center;
	}

	/* 购物车底部栏 */
	.cart-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		background: #333;
		color: #fff;
		display: flex;
		align-items: center;
		padding: 0 15px;
		z-index: 100;
	}

	.cart-icon {
		position: relative;
		margin-right: 15px;
	}

	.cart-badge {
		position: absolute;
		top: -8px;
		right: -8px;
		background: #1296db;
		color: #fff;
		border-radius: 50%;
		width: 18px;
		height: 18px;
		line-height: 18px;
		text-align: center;
		font-size: 12px;
	}

	.cart-total {
		flex: 1;
		font-weight: bold;
		font-size: 16px;
	}

	.cart-btn {
		background: #1296db;
		padding: 8px 20px;
		border-radius: 20px;
		font-size: 14px;
	}
</style>